package com.wgt.strategy.objSort;

import java.util.Arrays;
import java.util.List;

/**
 * Created by wgt on 2017/7/20.
 */
public class ObjSort {

    public static final int ASC = 1;
    public static final int DESC = 2;

    /**
     * 数组形式的冒泡排序
     * @param objArray
     * @param sortType
     */
    public static void sort(Object[] objArray,int sortType){
        if (sortType==ASC){
            ASCSort(objArray);
        }else{
            DESCSort(objArray);
        }
    }

    /**
     * ArrayList形式的冒泡排序
     * @param list
     * @param sortType
     */
    public static void sort(List list,int sortType){
        Object [] sortArray = list.toArray();
        sort(sortArray,sortType);
        list.clear();
        list.addAll(Arrays.asList(sortArray));
    }


    private static void ASCSort(Object[] datas){
        for(int i=datas.length;i>0;i--){
            for (int j=0;j<i-1;j++){
                if (datas[j] instanceof Comparable&&datas[j+1] instanceof Comparable){
                    if (((Comparable)datas[j]).compareTo((Comparable)datas[j+1])==1){
                        swap(datas,j,j+1);
                    }
                }

            }
        }
    }


    private static void DESCSort(Object[] datas){
        for (int i=0;i<datas.length;i++){
            for (int j=i;j>0;j--){
                if (datas[j] instanceof Comparable&&datas[j-1] instanceof Comparable) {
                    if (((Comparable) datas[j]).compareTo((Comparable) datas[j - 1]) == 1) {
                        swap(datas, j, j - 1);
                    }
                }
            }
        }
    }

    private static void swap(Object[] datas, int x, int y) {
        Object temp = datas[x];
        datas[x] = datas[y];
        datas[y] = temp;
    }
}
